from django.http import HttpResponse
from ...models.chat_roles import ChatRoles
from ...models.chat_model import ChatModel
from django.core.serializers import serialize
from ...utils.time_conversion import iso_to_times

import json


def roles_list(request):
    '''
    参数：enable=1
    '''
    chatroles_enable_str = request.GET.get('enable', None)
    if chatroles_enable_str is not None:
        all_chatroles = ChatRoles.objects.filter(enable=True)
    else:
        all_chatroles = ChatRoles.objects.all().order_by('sort')

    json_data_str = serialize('json', all_chatroles)
    json_data = json.loads(json_data_str)

    data = []
    for i in range(len(json_data)):
        json_data[i]['fields']['id'] = json_data[i]['pk']

        # 数据处理
        created_at_second = iso_to_times(json_data[i]['fields']['created_at'])
        updated_at_second = iso_to_times(json_data[i]['fields']['updated_at'])
        json_data[i]['fields']['created_at'] = created_at_second
        json_data[i]['fields']['updated_at'] = updated_at_second

        # 处理context字段
        if json_data[i]['fields']['context']:
            context_str_dumps = json_data[i]['fields']['context']
            context_list_loads = json.loads(context_str_dumps)
            json_data[i]['fields']['context'] = context_list_loads

        # 连表查询key name
        if json_data[i]['fields']['model_id'] is None:
            json_data[i]['fields']['model_id'] = 0
            json_data[i]['fields']['model_name'] = ""
        else:
            json_data[i]['fields']['model_name'] = all_chatroles[i].model_id.name

        data.append(json_data[i]['fields'])

    res_mes = {
        "code": 0,
        "data": data
    }
    res_mes_json = json.dumps(res_mes, ensure_ascii=False)
    return HttpResponse(res_mes_json)


def roles_save(request):
    '''
    save
    post
    '''
    if request.method == 'POST':
        json_b = request.body
        json_str = json_b.decode('utf-8')
        json_obj = json.loads(json_str)

        # 删除没必要的数据
        try:
            del json_obj['created_at']
            del json_obj['updated_at']
            del json_obj['model_name']
        except:
            pass

        if "model_id" not in json_obj:
            json_obj['model_id'] = None

        # 查询数据
        if "id" in json_obj:
            chatroles_instance_list = ChatRoles.objects.filter(id=json_obj['id'])
            if chatroles_instance_list:
                chatroles_instance = chatroles_instance_list[0]
            else:
                res_mes = {
                    "code": 1,
                    "message": "没有这个数据"
                }
                res_mes_json = json.dumps(res_mes, ensure_ascii=False)
                return HttpResponse(res_mes_json)
        else:
            chatroles_instance = ChatRoles()

        # 保存数据
        for key, value in json_obj.items():
            if key == "model_id":
                if value is None or value == 0 or not value:
                    chatroles_instance.model_id = None
                else:
                    chatmodel_instance = ChatModel.objects.get(id=value)
                    chatroles_instance.model_id = chatmodel_instance
            elif key == "context":
                if value:
                    context_list = json.dumps(value, ensure_ascii=False)
                    chatroles_instance.context = context_list
                else:
                    chatroles_instance.context = None
            else:
                code_str = "chatroles_instance.%s = '%s'" % (key, value)
                exec(code_str)

        try:
            chatroles_instance.save()
        except Exception as e:
            res_mes = {
                "code": 1,
                "message": e
            }
            res_mes_json = json.dumps(res_mes, ensure_ascii=False)
            return HttpResponse(res_mes_json)
        
        res_mes = {
            "code": 0
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)


def roles_remove(request):
    re_id = request.GET.get('id')
    try:
        del_obj = ChatRoles.objects.get(id=re_id)
        del_obj.delete()

        res_mes = {
            "code": 0
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)
    except Exception as e:
        res_mes = {
            "code": 1,
            "message": e
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)


def roles_set(request):
    if request.method == 'POST':
        json_b = request.body
        json_str = json_b.decode('utf-8')
        json_obj = json.loads(json_str)

        try:
            ChatRoles.objects.filter(id=json_obj['id']).update(enable=json_obj['value'])
        except Exception as e:
            res_mes = {
                "code": 1,
                "message": e
            }
            res_mes_json = json.dumps(res_mes, ensure_ascii=False)
            return HttpResponse(res_mes_json)

        res_mes = {
            "code": 0
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)


def roles_sort(request):
    if request.method == 'POST':
        json_b = request.body
        json_str = json_b.decode('utf-8')
        json_obj = json.loads(json_str)

        try:
            for index, ids in enumerate(json_obj['ids']):
                ChatRoles.objects.filter(id=ids).update(sort=json_obj['sorts'][index])
        except Exception as e:
            res_mes = {
                "code": 1,
                "message": e
            }
            res_mes_json = json.dumps(res_mes, ensure_ascii=False)
            return HttpResponse(res_mes_json)

        res_mes = {
            "code": 0
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)

